<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\ViewErrorBag;

class JsonReturn
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        /**@var \Illuminate\Http\Response $result**/
        $result = $next($request);
        $status = intval($result->status());
        if ($status !== 200) {
            if ($status === 302) {
                /** @var ViewErrorBag $errors */
                $errors = session('errors');
                $msgs = $errors->default->all();
                $res = [
                    'success' => false,
                    'message' => implode(' ', $msgs),
                ];
            } else {
                $exception = $result->exception;
                $res = [
                    'success' => false,
                    'message' => $result->status(),
                    'exception' => [
                        'file' => $exception->getFile(),
                        'line' => $exception->getLine(),
                        'error_msg' => $exception->getMessage(),
                    ],
                ];
            }
        } else {
            $return_data = $result->getOriginalContent();
            if (is_null($return_data)) {
                $return_data = [];
            }
    //        if (!is_array($return_data)) $return_data = [$return_data];
            if (is_array($return_data) && isset($return_data['error_msg'])) {
                $res = [
                    'success' => false,
                    'message' => $return_data['error_msg'],
                ];
            } else {
                $res = [
                    'success' => true,
                    'data' => $return_data,
                ];
            }
        }
        return Response::json($res);
    }
}
